#include "XMPPClient.h"

namespace cm_nat
{
    XMPPClient::XMPPClient()
        :m_client(NULL),
        m_listener(NULL)
    {

    }

    XMPPClient::~XMPPClient()
    {

    }

    void XMPPClient::registerListener( XMPPClientListener* p_listener )
    {
        m_listener = p_listener;
    }

    int XMPPClient::setup(std::string username, std::string pwd, std::string resource, std::string server, UInt16 serverPort )
    {
        m_username = username;
        m_password = pwd;
        m_resource = resource;
        m_server = server;
        m_serverPort = serverPort;

        m_bufferPool.setup(30,1024);

        JID jid;
        jid.setUsername( m_username );
        jid.setServer( m_server );
        jid.setResource( m_resource );

        m_client = new Client(jid, m_password, m_serverPort);

        m_client->setBufferPool(&m_bufferPool);

        //notify connection related info to 
        //up layer(XMPPCLient) is through ConnectionListener
        m_client->registerConnectionListener(this);

        m_client->logInstance().registerLogHandler(LogLevelDebug, LogAreaAll, this);

        m_client->disco()->setVersion( "ChipMind", CM_VERSION, "Linux");
        m_client->disco()->setIdentity("client", "bot");

        return CM_RES_SUCCESS;
    }

    int XMPPClient::teardown()
    {
        return CM_RES_SUCCESS;
    }

    int XMPPClient::connect()
    {
        bool res = false;

        res = m_client->connect();
        if( res == true ){
            return CM_RES_SUCCESS;
        }
        return CM_RES_FAIL;
    }

    int XMPPClient::disconnect()
    {
        m_client->disconnect();

        return CM_RES_SUCCESS;
    }

    ClientBase* XMPPClient::getClientBase()
    {
        return m_client;
    }

    void XMPPClient::handleLog( LogLevel level, LogArea area, const std::string& message )
    {
        g_log_root.warning(message);
    }

    void XMPPClient::onConnect()
    {
        poco_debug(g_log_nat, "XMPPClient::onConnect()" );
        if( m_listener ){
            m_listener->onConnect( this );
        }
    }

    void XMPPClient::onDisconnect( int e )
    {
        poco_debug(g_log_nat, "XMPPClient::onDisconnect()" );
        if( m_listener ){
            m_listener->onDisconnect( this );
        }
    }

    bool XMPPClient::onTLSConnect(const CertInfo& info )
    {
        return true;
    }

}